package com.caidan.search.interceptor;

import com.caidan.common.util.AuthContextHolder;
import com.caidan.framework.redis.key.UserProviderCacheKeyBuilder;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @项目名 CaiDanSearchSystem
 * @描述 自定义拦截器
 * @作者 小菜蛋
 * @时间 2024/12/2 19:55
 */
@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserProviderCacheKeyBuilder userProviderCacheKeyBuilder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        String authorization = request.getHeader("Authorization");
        log.info("用户信息 token :{}",authorization);
        try {
            String key = userProviderCacheKeyBuilder.buildUserMessageToken(authorization);
            String res = stringRedisTemplate.opsForValue().get(key);
            if (res == null) {
                AuthContextHolder.setUserId(null);
                return true;
            }
            Long userId = Long.parseLong(res);
            AuthContextHolder.setUserId(userId);
            return true;
        } catch (Exception e) {
            log.error("拦截器出现错误，详细信息 {}", e.getMessage());
            return false;
        }
    }
}